<?php
declare(strict_types=1);

namespace Sdk\YunWms;

use GuzzleHttp\Client;

class callYunWmsApiUtil extends Client
{
    private $appToken = '38c5466d378a55c9fe56f04700264ef1';

    private $appKey = 'a6d92db72c0f1c595a5ece088f6bc935';

    private const URL = 'https://szkyt.yunwms.com/default/svc/web-service';

    public function __construct(array $config = [])
    {
        parent::__construct($config);
    }

    public function callApi($service, $params = [])
    {
        if (is_array($params)) {
            $params = json_encode($params, JSON_UNESCAPED_UNICODE);
        }
        $data = $this->buildXml($service, $params);
        $response = $this->post(static::URL, [
            'headers' => [
                'Content-Type' => 'text/xml; charset=utf-8',
            ],
            'body' => $data
        ]);
        if ($response->getStatusCode() == 200) {
            $text = $response->getBody()->getContents();
            $xmlDoc = simplexml_load_string($text);
            $xmlResult = $xmlDoc->xpath('//response')[0];
            $xmlResult = (array)$xmlResult;
            $result = $xmlResult[0];
            return json_decode($result, true);
        } else {
            throw new \Exception("请求失败");
        }
    }


    public function buildXml($service, $params)
    {
        $xml = <<<EOD
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.example.org/Ec/">
       <SOAP-ENV:Body>
          <ns1:callService>
                  <paramsJson>
                       $params
                   </paramsJson>
                   <appToken>$this->appToken</appToken>
                   <appKey>$this->appKey</appKey>
                   <service>$service</service>
                 </ns1:callService>
             </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
EOD;
        return $xml;
    }
}